<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center">
                        <div v-if="!route.query.id">新增物料领用单</div>
                        <div v-else>
                            <span class="text-sm mr-2" style="color: var(--el-text-color-regular)">
                                物料领用单编码:
                            </span>
                            <el-tag>{{ route.query.code }}</el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div class="flex items-center" v-if="Boolean(!route.query.readonly)">
                        <el-button type="primary" @click="submitForm">保 存</el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form :model="form" :rules="rules" :disabled="Boolean(route.query.readonly)"
                            ref="materialReceiptRef" label-width="100px">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="领用机台" prop="machineName">
                                        <el-input v-model="form.machineName" placeholder="请选择领用机台"
                                            @click="() => { searchVisible = true }" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="所属车间" prop="workshopName">
                                        <el-input v-model="form.workshopName" disabled placeholder="自动带出" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="出库日期" prop="outDate">
                                        <el-date-picker style="width: 100%" v-model="form.outDate"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" type="datetime"
                                            placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>

                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="领用部门" prop="deptId">
                                        <el-tree-select style="width: 100%" v-model="form.deptId" :data="deptOptions"
                                            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                                            placeholder="请选择领用部门" check-strictly />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="制单人" prop="createBy">
                                        <el-input v-model="form.createBy" disabled placeholder="自动带出" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="创建时间" prop="createTime">
                                        <el-date-picker style="width: 100%" v-model="form.createTime" type="datetime"
                                            format="YYYY-MM-DD HH:mm:ss" disabled value-format="YYYY-MM-DD HH:mm:ss"
                                            placeholder="请选择时间" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
                <el-collapse-item disabled  title="领用明细" name="2">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">领用明细</span>
                    </template>
                    <el-button style="margin-bottom: 10px;" type="primary" size="small" @click="handleMateriel"
                        :disabled="Boolean(route.query.readonly)">从物料库选择</el-button>
                    <el-table v-loading="loading" class="table-form" :data="mesMaterialUsedetailList"
                        :header-cell-class-name="must">
                        <el-table-column label="序号" width="60" type="index" align="center" :header-cell-class-name="must">
                        </el-table-column>
<!--                        <el-table-column label="入库单编码" min-width="120" align="center" prop="inCode"-->
<!--                            :show-overflow-tooltip="true" />-->
                        <el-table-column label="物料分类" min-width="150" align="center" prop="className"
                            :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column label="物料编码" min-width="150" align="center" prop="materialCode"
                            :show-overflow-tooltip="true">

                        </el-table-column>
                        <el-table-column label="物料名称" min-width="150" align="center" prop="materialName">
                        </el-table-column>
                        <el-table-column label="规格型号" min-width="120" align="center" prop="specs">
                        </el-table-column>
                        <el-table-column label="单位" min-width="120" align="center" prop="unit">
                            <template #default="scope">
                                <dict-tag :options="mes_material_unit" :value="scope.row.unit" />
                            </template>
                        </el-table-column>
                        <el-table-column label="领用数量" prop="quantity" align="center" width="130">
                            <template #default="scope">
                                <el-input v-model="scope.row.quantity" @input="SumPrice(scope.row)"
                                    :disabled="Boolean(route.query.readonly)" :max="scope.row.stockNum" type="number"
                                    placeholder="请输入领用数量" />
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" prop="authorityPrice" align="center" width="130">
                            <template #default="scope">
                                <el-input v-model="scope.row.authorityPrice" disabled type="number" placeholder="自动带出" />
                            </template>
                        </el-table-column>
                        <!-- <el-table-column label="库存数量" prop="stockNum" disabled align="center" width="120">
                        </el-table-column> -->
                        <el-table-column label="折合金额(元)" prop="amount" disabled align="center" width="120">
                        </el-table-column>
                        <el-table-column label="备注" prop="remark" align="center" width="120">
                            <template #default="scope">
                                <el-input v-model="scope.row.remark" :disabled="Boolean(route.query.readonly)"
                                    placeholder="请输入备注" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-tooltip content="删除" placement="top">
                                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                                        :disabled="Boolean(route.query.readonly)"></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-collapse-item>
            </el-collapse>
        </el-card>

        <SearchWorkBench :visible="searchVisible" @changeUpdate="changeSearchWorkBenchData"
            @cancel="() => { searchVisible = false }"></SearchWorkBench>
        <searchMaterialReceipt :visible="searchMaterialReceiptVisible" @changeUpdate="changesearchMaterialReceipt"
            :receiptList="receiptList" @cancel="() => { searchMaterialReceiptVisible = false }"></searchMaterialReceipt>

    </div>
</template>
<script setup>
import { getMaterialuse, addMaterialuse, updateMaterialuse } from '@/api/storage/materialRequisition.js'
import { deptTreeSelect } from "@/api/system/user";
import SearchWorkBench from '@/components/SearchWorkBench'
import searchMaterialReceipt from './searchMaterialReceipt'
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
const tagsViewStore = useTagsViewStore()
const { proxy } = getCurrentInstance();
const { mes_material_unit, mes_paper_specs } = proxy.useDict('mes_material_unit', 'mes_paper_specs');
const route = useRoute()
const router = useRouter()
const activeNames = ['1', '2']
const materialReceiptRef = ref(null)
const searchMaterialReceiptVisible = ref(false)
const loading = ref(false)
const userInfo = useUserStore()
const mesMaterialUsedetailList = ref([])
const searchVisible = ref(false)
const deptOptions = ref([])
const receiptList = ref([])
const data = reactive({
    form: {
    },
    rules: {
        machineName: [{ required: true, message: "领用机台不能为空", trigger: "change" },],
        outDate: [{ required: true, message: "出库日期不能为空", trigger: ["blur", "change"] }],
        deptId: [{ required: true, message: "领用部门不能为空", trigger: ["change"] }],
    }
});
const { form, rules } = toRefs(data);
if (route.query.id) {
    getMaterialuse(route.query.id).then(response => {
        form.value = response.data
        //20240314 再次选择物料库是之前选择的在物料库勾选的不对
        //mesMaterialUsedetailList.value = response.data.mesMaterialUsedetailList
        response.data.mesMaterialUsedetailList.forEach(ele => {
            ele.id = ele.materialId;
            mesMaterialUsedetailList.value.push(ele);
        });

    })

} else {
    form.value = {}
    form.value.createBy = userInfo.name

}

// 获取当前时间
const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    form.value.outDate=`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
getCurrentDateTime()
/** 查询部门下拉树结构 */
function getDeptTree() {
    deptTreeSelect().then(response => {
        deptOptions.value = response.data;
    });
};
// 选中机台
const changeSearchWorkBenchData = (row) => {
    console.log('row', row)
    form.value.machineName = row.machineName
    form.value.machineId = row.pid
    form.value.workshopName = row.workshopName
    searchVisible.value = false
}
const changesearchMaterialReceipt = (row) => {
    console.log('row', row);
    //清空之前的选择
    mesMaterialUsedetailList.value = []
    row.forEach(ele => {
        delete ele.quantity;
        delete ele.amount;
        ele.authorityPrice = ele.price;
        ele.quantity = ele.stockNum
        ele.materialindetailId = ele.id;
        ele.materialId = ele.id;
        mesMaterialUsedetailList.value.push(ele);
        SumPrice(ele)
    });
    mesMaterialUsedetailList.value = uniqueByMaterialId(mesMaterialUsedetailList.value)
    searchMaterialReceiptVisible.value = false;
}
const uniqueByMaterialId = (list) => {
    const seenMaterialIds = {};
    return list.reduce((acc, curr) => {
        if (!seenMaterialIds[curr.id]) {
            seenMaterialIds[curr.id] = true;
            acc.push(curr);
        }
        return acc;
    }, []);
};

//选择入库单 修改成从物料库选择
const handleMateriel = () => {
    receiptList.value = mesMaterialUsedetailList.value
    searchMaterialReceiptVisible.value = true
}
const SumPrice = (row) => {

    if (Number(row.quantity) > row.stockNum) {
        row.quantity = null
        ElMessage({
            message: '领用数量不能大于库存数量',
            type: 'warning',
        })
        return
    }

    //row.amount = Number((Number(row.quantity) * Number(row.authorityPrice)).toFixed(4))
    row.amount=row.quantity==undefined?0:Number((Number(row.quantity) * Number(row.authorityPrice)).toFixed(4));

    console.log('amount:', row.amount);
}
// 删除
// const handleDelete = (row) => {
//     proxy.$modal.confirm('是否确认删除该数据？').then(function () {
//         mesMaterialUsedetailList.value = mesMaterialUsedetailList.value.filter(item => item.id !== row.id)
//         proxy.$modal.msgSuccess("删除成功");
//     })
// }
const handleDelete = (row) => {
    proxy.$modal.confirm('是否确认删除该数据？').then(function () {
        const index = mesMaterialUsedetailList.value.findIndex(item => item.code == row.code);
        if (index != -1) {
            mesMaterialUsedetailList.value.splice(index, 1);
            proxy.$modal.msgSuccess("删除成功");
        } else {
            proxy.$modal.msgError("未找到要删除的数据");
        }
    });
}
// 确认
const submitForm = () => {
    const screen = mesMaterialUsedetailList.value.find(item => {
        return !item.quantity
    })
    if (screen) {
        ElMessage({
            message: '请填写领用明细中的领用数量字段',
            type: 'warning',
        })
        return
    }
    materialReceiptRef.value.validate(valid => {
        if (valid) {
            if (route.query.id) {
                updateMaterialuse({ ...form.value, mesMaterialUsedetailList: mesMaterialUsedetailList.value }).then(res => {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    goBack()
                })
            } else {
                addMaterialuse({ ...form.value, status: 0, mesMaterialUsedetailList: mesMaterialUsedetailList.value }).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    goBack()
                })
            }
        }
    });
}

const must = (obj) => {
    let mustColumns = []
    mustColumns = [7];
    if (mustColumns.includes(obj.columnIndex)) {
        return 'must';
    }
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
   // router.go(-1)
    if(route.query.moduleCode=="searchMaterialRequisition") {
        router.push('/material/searchMaterialRequisition')
    }else{
        router.push('/material/materialRequisition')
    }
    // router.push('/storage/materialRequisition')
}
getDeptTree()
</script>

<style lang="scss" scoped>
.footer {
    text-align: center;
}

:deep(.el-pagination) {
    position: unset;
}

.table-form :deep(.el-form-item) {
    margin-bottom: 0;
}

:deep(.el-table th.must div:before) {
    content: '*';
    color: #ff1818;
}
</style>